import {AddToCartPayload, CartProduct, CheckoutStatus} from "@/store";
import {Commit} from "vuex";
import * as types from '../mutation-type'
import shop from "@/api/shop";

interface Shape {
    id: number,
    quantity: number
}

interface CheckoutFailurePayload {
    savedCartItems: Shape[]
}

export interface State {
    added: Shape[],
    checkoutStatus: CheckoutStatus
}
// 初始化状态
const initState: State = {
    added: [],
    checkoutStatus: null
};

const getters = {
    checkoutStatus: (state: State) => state.checkoutStatus
};

const actions = {
    checkout (context: {commit: Commit, state: State }, products: CartProduct[]) {
        // 保存数据
        const failurePayload: CheckoutFailurePayload = {
            savedCartItems: [...context.state.added]
        };
        // 清空购物车数据
        context.commit(types.CHECKOUT_REQUEST);
        // 发起请求, 请求成功，更改结算状态；请求失败，恢复购物车数据
        // 是不是可以先不清空，请求成功后在清除？？ 失败就不进行操作
        shop.buyProducts(
            products,
            () => context.commit(types.CHECKOUT_SUCCESS),
            () => context.commit(types.CHECKOUT_FAILURE, failurePayload))
    }
};

const mutations = {
    // 加入购物车
    [types.ADD_TO_CART](state: State, payload: AddToCartPayload) {
        // 加入后，清空上一次的结算状态
        state.checkoutStatus = null;
        // 判断购物车是否有相同商品，不同就添加，相同则数量+1，库存-1
        const hasRecord = state.added.find((p) => p.id === payload.id);
        if (!hasRecord) {
            state.added.push({
                id: payload.id,
                quantity: 1
            })
        } else {
            hasRecord.quantity++
        }

    },
    // 点结算时，清空购物车的数据，然后在发起请求
    [types.CHECKOUT_REQUEST](state: State) {
        state.added = [];
        state.checkoutStatus = null
    },
    // 结算请求成功后，修改结算状态
    [types.CHECKOUT_SUCCESS](state: State) {
        state.checkoutStatus = 'successful'
    },
    // 结算请求失败，修改状态，恢复购物车数据
    [types.CHECKOUT_FAILURE](state: State, cartPayload: CheckoutFailurePayload) {
        state.added = cartPayload.savedCartItems;
        state.checkoutStatus = 'failed'
    }
};

export default {
    state: initState,
    getters,
    actions,
    mutations
}
